package cn.jpanda.elastic.job.autoconfigure.configuration;

import cn.jpanda.elastic.job.autoconfigure.ElasticJobAutoConfiguration;
import cn.jpanda.elastic.job.autoconfigure.annotations.EnableElasticJob;
import cn.jpanda.elastic.job.autoconfigure.constants.ConfigurationConstants;
import cn.jpanda.elastic.job.autoconfigure.listener.JobSchedulerInitListener;
import cn.jpanda.elastic.job.autoconfigure.strategy.DataFlowJobParseAnnotationHandlerStrategy;
import cn.jpanda.elastic.job.autoconfigure.strategy.ScriptJobParseAnnotationHandlerStrategy;
import cn.jpanda.elastic.job.autoconfigure.strategy.SimpleJobParseAnnotationHandlerStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;

/**
 * 自动导入选择器，将会根据{@link EnableElasticJob#enabled()}的值进行动态加载ElasticJob配置
 *
 * @author Hanqi <jpanda@aliyun.com>
 * @since 2018/9/18 15:49
 */
@Slf4j
public class ElasticJobImportSelector implements ImportSelector {


    public String[] selectImports(AnnotationMetadata importingClassMetadata) {

        // 需要处理的注解名称
        Class<?> annotationType = EnableElasticJob.class;

        // 获取EnableElasticJob注解中的参数集合
        AnnotationAttributes annotationAttributes = AnnotationAttributes.fromMap(
                importingClassMetadata.getAnnotationAttributes(annotationType.getName(), false)
        );

        // 常规场景下,该参数永远不会为null.
        assert annotationAttributes != null;
        // 根据注解的ENABLED_ATTR_NAME参数的值，来确定是否引入自动配置类。
        boolean enabled = annotationAttributes.getBoolean(ConfigurationConstants.ENABLED_ELASTIC_JOB_ENABLED_ATTR_NAME);

        if (!enabled) {
            log.debug("检测到{}注解中的{}值为false,系统中Elastic Job 配置将不会生效"
                    , EnableElasticJob.class.getCanonicalName()
                    , ConfigurationConstants.ENABLED_ELASTIC_JOB_ENABLED_ATTR_NAME
            );
            return new String[0];
        }
        return new String[]{
                ConfigurationConstants.ZOOKEEPER_PROPERTIES_CONFIGURATION
                , ElasticJobAutoConfiguration.class.getCanonicalName()
                , JobSchedulerInitListener.class.getCanonicalName()
                , SimpleJobParseAnnotationHandlerStrategy.class.getCanonicalName()
                , ScriptJobParseAnnotationHandlerStrategy.class.getCanonicalName()
                , DataFlowJobParseAnnotationHandlerStrategy.class.getCanonicalName()
        };
    }

}
